/*
 * @Author: your name
 * @Date: 2021-04-15 20:12:17
 * @LastEditTime: 2021-04-24 20:56:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /first_flutter_app/lib/indexPage/table.dart
 */

// import 'package:first_flutter_app/util/IconText.dart';
import 'package:first_flutter_app/controller/orderPageController.dart';
import 'package:first_flutter_app/controller/tablePageController.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:giffy_dialog/giffy_dialog.dart';

class tableShow extends StatelessWidget {
  Map tableInfo = {};
  int tableIndex = 0;
  tableShow({Key key, this.tableInfo, this.tableIndex}) : super(key: key);

  int showColorFlage = 1;
  MaterialColor cc = Colors.grey;

  var colorMap = {
    1: Colors.grey, //空闲态
    2: Colors.orange, //已开台
    // 3: Colors.green, // 已下单
    3: Colors.purple, // 已结账
  };

  Map<int, Widget> tableMainMap = {
    1: Container(
      child: Center(
        child: Icon(Icons.add),
      ),
    ), //空闲态
    2: Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [Text("￥100"), Text("4h53m")],
        ),
      ),
    ), //已开台
    // 3: Container(
    //   child: Center(
    //     child: Icon(Icons.post_add_sharp),
    //   ),
    // ), // 已下单
    3: Container(
      child: Center(
        child: Icon(Icons.cleaning_services),
      ),
    ), // 已结账
  };

  Widget tableMainShow(BuildContext context) {
    if (OrderController.oc.tableList[tableIndex]['state'] == 1) {
      return InkWell(
        onTap: () {
          OrderController.oc.tableList[tableIndex] = tableInfo;
          OrderController.oc.currentSelectTableIndex = tableIndex;
          if(OrderController.oc.tableList[tableIndex]['state'] == 1) {
            OrderController.oc.tableList[tableIndex]['state'] = 2;
            OrderController.oc.currentSelectTable = OrderController.oc.tableList[tableIndex];
            Get.toNamed("/orderPage?tableListIndex="+tableIndex.toString());
          } else {
            if (OrderController.oc.tableList[tableIndex]['state'] == 2) {
              OrderController.oc.currentSelectTable = OrderController.oc.tableList[tableIndex];
              Get.toNamed("/orderPage?tableListIndex="+tableIndex.toString());
            }
          }
        },
        child: Container(
          child: Center(
            child: Icon(Icons.add),
          ),
        ),
      );
    }
    if (OrderController.oc.tableList[tableIndex]['state'] == 2) {
      return Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            InkWell(
              child: Icon(Icons.open_in_new),
              onTap: () {
                // OrderController.oc.currentSelectTable = OrderController.oc.tableList[tableIndex];
                OrderController.oc.currentSelectTableIndex = tableIndex;
                Get.toNamed("/orderPage?tableListIndex="+tableIndex.toString());
              },
            ),
            InkWell(
              child: Icon(Icons.cancel_outlined),
              onTap: () {
                showDialog(
                    context: context,
                    builder: (_) => AssetGiffyDialog(
                      // key: keys[5],
                      // Image.asset("images/1.png", fit: BoxFit.cover)
                      buttonOkText: Text("确定",
                          style: TextStyle(color: Colors.white)),
                      buttonCancelText: Text("再想想",
                          style: TextStyle(color: Colors.white)),
                      image: Image.asset(
                        'images/iconfont.gif',
                        fit: BoxFit.cover,
                      ),
                      title: Text(
                        '操作',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: ScreenUtil().setSp(100),
                            fontWeight: FontWeight.w600),
                      ),
                      // entryAnimation: EntryAnimation.DEFAULT,
                      description: Text(
                        '确定清台吗?',
                        textAlign: TextAlign.center,
                        style:
                        TextStyle(fontSize: ScreenUtil().setSp(150)),
                      ),
                      onOkButtonPressed: () {
                        OrderController.oc.cleanTableOrderDetail();
                        OrderController.oc.setNoShowOrderDetails();
                        Navigator.of(context).pop();
                      },
                    )
                );
              },
            ),
          ],
        ),
      );
    }
    if (OrderController.oc.tableList[tableIndex]['state'] == 3) {
      return InkWell(
        child: Container(
          child: Center(
            child: Icon(Icons.remove_circle),
          ),
        ),
      );
    }
  }

  Widget DraggableTable(BuildContext context) {
    return LongPressDraggable(
      ignoringFeedbackSemantics: true,
      data: tableIndex,
      child: DragTarget<int>(
        builder: (context, data, rejects) {
          return Material(
              child: GetBuilder<OrderController>(
                builder: (_) => Column(
                  children: [
                    Container(
                        margin: EdgeInsets.only(top: 5),
                        width: ScreenUtil().setWidth(145),
                        height: ScreenUtil().setHeight(80),
                        decoration: BoxDecoration(
                          border: new Border.all(color: Colors.black12, width: 0.5),
                          color: colorMap[OrderController.oc.tableList[tableIndex]['state']],
                          borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(10.0),
                              topRight: Radius.circular(10.0)), //
                        ),
                        child: InkWell(
                            onTap: () {
                              OrderController.oc.setShowOrderDetails(tableIndex: tableIndex, clickType: 'table');
                            },
                            child: Flex(
                              direction: Axis.horizontal,
                              children: [
                                // 桌台名称
                                Expanded(
                                    flex: 6,
                                    child: Container(
                                        margin: EdgeInsets.only(left: 5.0),
                                        child: Text(
                                          tableInfo["tableName"],
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 13.0,
                                          ),
                                          overflow: TextOverflow.ellipsis,
                                        ))),
                                // 占台人数
                                Expanded(
                                    flex: 2,
                                    child: Text(
                                        tableInfo["person"].toString() +
                                            "/" +
                                            tableInfo["tableMaxOcup"].toString(),
                                        style: TextStyle(color: Colors.white, fontSize: 10.0))),
                              ],
                            )
                        )
                    ),
                    Container(
                      width: ScreenUtil().setWidth(145),
                      height: ScreenUtil().setHeight(200),
                      decoration: BoxDecoration(
                        border: new Border.all(color: Colors.black12, width: 0.5),
                        color: Colors.white,
                        borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(10.0),
                            bottomRight: Radius.circular(10.0)), //
                      ),
                      child: tableMainShow(context),
                    ),
                  ],
                ),
              )
          );
        },
        // 手指拖着一个widget从另一个widget头上滑走时会调用
        onLeave: (data) {
          print('---$data is Leaving item ---');
        },
        // 松手时，是否需要将数据给这个widget，因为需要在拖动时改变UI，所以在这里直接修改数据源
        onWillAccept: (data) {
          print('---(target) will accept item (drag)$data---');
          return true;
        },
        // 松手时，如果onWillAccept返回true，那么就会调用
        onAccept: (data) {
          OrderController.oc.canDraggableTable = false;
          if(OrderController.oc.tableList[this.tableIndex]['state'] == 1) {
            OrderController.oc.tableList[this.tableIndex]['orderDetail'] = OrderController.oc.tableList[data]['orderDetail'];
            OrderController.oc.tableList[this.tableIndex]['state'] = OrderController.oc.tableList[data]['state'];
          } else {
            if(OrderController.oc.tableList[this.tableIndex]['orderDetail'].length>0) {
              var newOrderDetail = OrderController.oc.tableList[this.tableIndex]['orderDetail'];
              var oldOrderDetail = OrderController.oc.tableList[data]['orderDetail'];
              for (var op in oldOrderDetail) {
                var newOne = true;
                for(var np in newOrderDetail) {
                  if(op['id'] == np['id']) {
                    np['qty'] += 1;
                    np['price'] = np['qty'] * np['original_price'];
                    newOne = false;
                  }
                }
                if (newOne) {
                  newOrderDetail.add(op);
                }
              }
              OrderController.oc.tableList[this.tableIndex]['orderDetail'] = newOrderDetail;
              OrderController.oc.tableList[this.tableIndex]['state'] = 2;
            } else {
              OrderController.oc.tableList[this.tableIndex]['orderDetail'] = OrderController.oc.tableList[data]['orderDetail'];
              OrderController.oc.tableList[this.tableIndex]['state'] = OrderController.oc.tableList[data]['state'];
            }
          }
          OrderController.oc.currentSelectTableIndex = this.tableIndex;
          OrderController.oc.tableList[data]['orderDetail'] = [];
          OrderController.oc.tableList[data]['state'] = 1;
          OrderController.oc.setDraggableTable();
          print('---(onAccept) accept item (drag)$data---');
          // TODO 松手时交换数据并刷新 UI
        },
      ),
      feedback: Material(
        child: GetBuilder<OrderController>(
          builder: (_) => Column(
            children: [
              Container(
                  margin: EdgeInsets.only(top: 5),
                  width: ScreenUtil().setWidth(145),
                  height: ScreenUtil().setHeight(80),
                  decoration: BoxDecoration(
                    border: new Border.all(color: Colors.black12, width: 0.5),
                    color: colorMap[OrderController.oc.tableList[tableIndex]['state']],
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10.0),
                        topRight: Radius.circular(10.0)), //
                  ),
                  child: Flex(
                    direction: Axis.horizontal,
                    children: [
                      // 桌台名称
                      Expanded(
                          flex: 6,
                          child: Container(
                              margin: EdgeInsets.only(left: 5.0),
                              child: Text(
                                tableInfo["tableName"],
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 13.0,
                                ),
                                overflow: TextOverflow.ellipsis,
                              ))),
                      // 占台人数
                      Expanded(
                          flex: 2,
                          child: Text(
                              tableInfo["person"].toString() +
                                  "/" +
                                  tableInfo["tableMaxOcup"].toString(),
                              style: TextStyle(color: Colors.white, fontSize: 10.0))),
                    ],
                  )
              ),
              Container(
                  width: ScreenUtil().setWidth(145),
                  height: ScreenUtil().setHeight(200),
                  decoration: BoxDecoration(
                    border: new Border.all(color: Colors.black12, width: 0.5),
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(10.0),
                        bottomRight: Radius.circular(10.0)), //
                  ),
                  child: tableMainShow(context)
              ),
            ],
          )
        ),
      ),
      childWhenDragging: Material(
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 5),
              width: ScreenUtil().setWidth(145),
              height: ScreenUtil().setHeight(80),
              decoration: BoxDecoration(
                color: Colors.grey,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(10.0),
                    topRight: Radius.circular(10.0)), //
              ),
            ),
            Container(
              width: ScreenUtil().setWidth(145),
              height: ScreenUtil().setHeight(200),
              decoration: BoxDecoration(
                color: Colors.grey,
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(10.0),
                    bottomRight: Radius.circular(10.0)), //
              ),
            ),
          ],
        ),
      ),
      onDragStarted: () {
        print("onDragStarted");
      },
      onDragEnd: (DraggableDetails details) {
        print("onDragEnd : $details");
      },
      onDraggableCanceled: (Velocity velocity, Offset offset) {
        print('onDraggableCanceled velocity:$velocity,offset:$offset');
      },
      onDragCompleted: () {
        print('onDragCompleted');
      },
    );
  }

  Widget normalTable(BuildContext context) {
    return Material(
        child: GetBuilder<OrderController>(
          builder: (_) => Column(
            children: [
              Container(
                  margin: EdgeInsets.only(top: 5),
                  width: ScreenUtil().setWidth(145),
                  height: ScreenUtil().setHeight(80),
                  decoration: BoxDecoration(
                    border: new Border.all(color: Colors.black12, width: 0.5),
                    color: colorMap[OrderController.oc.tableList[tableIndex]['state']],
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10.0),
                        topRight: Radius.circular(10.0)), //
                  ),
                  child: InkWell(
                      onTap: () {
                        OrderController.oc.setShowOrderDetails(tableIndex: tableIndex, clickType: 'table');
                        print(OrderController.oc.showOrderDetails);
                      },
                      child: Flex(
                        direction: Axis.horizontal,
                        children: [
                          // 桌台名称
                          Expanded(
                              flex: 6,
                              child: Container(
                                  margin: EdgeInsets.only(left: 5.0),
                                  child: Text(
                                    tableInfo["tableName"],
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 13.0,
                                    ),
                                    overflow: TextOverflow.ellipsis,
                                  ))),
                          // 占台人数
                          Expanded(
                              flex: 2,
                              child: Text(
                                  tableInfo["person"].toString() +
                                      "/" +
                                      tableInfo["tableMaxOcup"].toString(),
                                  style: TextStyle(color: Colors.white, fontSize: 10.0))),
                        ],
                      )
                  )
              ),
              Container(
                width: ScreenUtil().setWidth(145),
                height: ScreenUtil().setHeight(200),
                decoration: BoxDecoration(
                  border: new Border.all(color: Colors.black12, width: 0.5),
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                      bottomLeft: Radius.circular(10.0),
                      bottomRight: Radius.circular(10.0)), //
                ),
                child: tableMainShow(context),
              ),
            ],
          ),
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<OrderController>(
        builder: (_) => OrderController.oc.canDraggableTable?DraggableTable(context):normalTable(context)
    );
  }

}
